package middleware

import (
	"errors"
	"strings"

	"gitee.com/cyanbleeze/go-image-management/pkg/app"
	"gitee.com/cyanbleeze/go-image-management/pkg/errcode"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		res := app.NewResponse(c)
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			res.ToErrorResponse(errcode.InvalidParams.WithDetails("缺少token"))
			c.Abort()
			return
		}
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			res.ToErrorResponse(errcode.InvalidParams.WithDetails("缺少token"))
			c.Abort()
			return
		}

		claims, err := app.ParseToken(parts[1])
		if err != nil {
			if errors.Is(err, jwt.ErrTokenMalformed) || errors.Is(err, jwt.ErrTokenSignatureInvalid) {
				res.ToErrorResponse(errcode.UnauthorizedTokenError)
			} else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) {
				res.ToErrorResponse(errcode.UnauthorizedTokenTimeout)
			} else {
				res.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
			}
			c.Abort()
			return
		}

		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Next()
	}
}

func JWTAuthButContinueMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			c.Next()
			return
		}
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.Next()
			return
		}

		claims, err := app.ParseToken(parts[1])
		if err != nil {
			c.Next()
			return
		}

		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Next()
	}
}
